<template>
  <BoTable
    :columns="columns"
    :request="getLightweightHealthList"
    ref="tableRef"
    row-key="reportId"
    show-index
  >
    <template #toolbars>
      <Space>
        <Button type="primary" @click="onGenerateReport"> 生成报告 </Button>
      </Space>
    </template>
  </BoTable>
  <!-- 生成报告弹窗 -->
  <FormModal :columns="items"></FormModal>
  <!-- 预览pdf -->
  <BoPreviewPdf
    title="预览PDF"
    :iframe-url="pdfUrl"
    :loading="loading"
    v-model:open="visible"
  ></BoPreviewPdf>
</template>
<route lang="json">
{
  "name": "lightweight-structure",
  "meta": {
    "title": "轻量化结构台阵观察评估报告"
  }
}
</route>
<script setup lang="tsx">
import { computed, ref } from 'vue';
import { getDeviceProjectSelect } from '@/api';
import { useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { listToEnum, listToOption } from '@boeyo/shared';
import { BoFormProps, BoPreviewPdf, BoTable, BoTableProps } from '@boeyo/ui';
import { Button, Image, Modal, Space, Tree, message } from 'ant-design-vue';
import {
  fetchStructureTree,
  getEarthquakeReport,
  getEventData,
  getGenerateReport,
  getLightweightHealthList,
} from './api';

interface Tree {
  id: number;
  children: Tree[];
  [key: string]: any;
}

const tableRef = ref();

const dictArr = ['report_type'];

const { reportTypeOptions } = useDicts(dictArr);

const treeData = ref([]);
const projectOptions = ref<any[]>([]);
const projectEnum = ref<Record<string, any>>({});
// 事件类型（根据projectId获取）
const eventOptions = ref<any[]>([]);
const init = async () => {
  getDeviceProjectSelect().then(({ data }) => {
    projectOptions.value = listToOption(data, 'name', 'projectId');
    projectEnum.value = listToEnum(data, 'name', 'projectId');
  });

  // 获取监测阵树形结构
  const res = await fetchStructureTree();
  treeData.value = formatTree(res.data, {
    label: 'structureName',
    value: 'id',
    disabled(data) {
      return ['1', '2'].includes(data.monitoringType);
    },
  });
};
init();

const findTree = (key, tree: Tree[]) => {
  const result = {};
  const stack = [...tree];
  while (stack.length > 0) {
    const node = stack.pop();
    if (node.children?.length) {
      stack.unshift(...node.children);
    }
    if (node.value === key) {
      Object.assign(result, node);
      break;
    }
  }
  return result as Tree;
};

/**
 * 格式化监测阵树形结构数据
 * @param tree
 * @param opt
 */
const formatTree = (
  tree: Tree[],
  opt: {
    label?: string;
    value?: string;
    children?: string;
    disabled: (data?: Record<string, any>) => boolean;
  },
) => {
  const {
    label = 'label',
    value = 'value',
    disabled = () => false,
    children = 'children',
  } = opt;

  const result = [];
  const stack = [...tree];
  const nodeMap = new Map();

  while (stack.length > 0) {
    const node = stack.shift();
    const formattedNode = {
      title: node[label],
      key: node[value],
      ...node,
      label: node[label],
      value: node[value],
      disabled: disabled(node),
      children: [],
    };
    nodeMap.set(node, formattedNode);
    const parentNode = nodeMap.get(node.parent);
    if (parentNode) {
      parentNode.children.push(formattedNode);
    } else {
      result.push(formattedNode);
    }
    if (node[children]) {
      node[children].forEach((child: any) => {
        child.parent = node;
        stack.push(child);
      });
    }
  }

  return result;
};

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '报告名称',
    dataIndex: 'reportName',
  },
  {
    title: '所属监测阵',
    dataIndex: 'structureName',
    hideInSearch: true,
  },
  {
    title: '生成时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions: [
      {
        text: '预览',
        onClick(record) {
          onPreview(record);
        },
      },
      {
        text: '下载',
        onClick(record) {
          onDownload(record);
        },
      },
    ],
  },
]);

const { FormModal, open } = useFormModal({
  column: 1,
  size: 'small',
});
// 生成报告时projectId
const projectId = ref(0);
const items = computed<BoFormProps['columns']>(() => [
  {
    title: '报告名称',
    dataIndex: 'reportName',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入报告名称',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入报告名称',
    },
  },
  {
    title: '监测阵',
    dataIndex: 'structureId',
    valueType: 'treeSelect',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择监测阵',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请选择监测阵',
      treeData: treeData.value,
      onChange(value) {
        if (!value) {
          eventOptions.value = [];
          return;
        }
        const result = findTree(value, treeData.value);
        projectId.value = result.projectId;
        getEventData(result.projectId).then(({ data }) => {
          eventOptions.value = listToOption(data, 'content', 'generateId');
        });
      },
    },
  },
  // {
  //   title: '所属项目',
  //   dataIndex: 'projectId',
  //   valueType: 'select',
  //   formItemProps: {
  //     rules: [
  //       {
  //         required: true,
  //         message: '请选择所属项目',
  //         trigger: 'blur',
  //       },
  //     ],
  //   },
  //   fieldProps: {
  //     placeholder: '请选择所属项目',
  //     options: projectOptions.value,
  //     onChange(projectId) {
  //       // 获取事件类型
  //       getEventData(projectId).then(({ data }) => {
  //         eventOptions.value = listToOption(data, 'content', 'generateId');
  //         console.log(eventOptions.value, 'eventOptions.value');
  //       });
  //     },
  //   },
  // },
  // {
  //   title: '报告类型',
  //   dataIndex: 'reportType',
  //   valueType: 'radio',
  //   formItemProps: {
  //     rules: [
  //       {
  //         required: true,
  //         message: '请选择报告类型',
  //         trigger: 'blur',
  //       },
  //     ],
  //   },
  //   fieldProps: {
  //     placeholder: '请选择报告类型',
  //     options: reportTypeOptions.value,
  //   },
  // },
  {
    title: '事件类型',
    dataIndex: 'generateId',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择事件类型',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请选择事件类型',
      options: eventOptions.value,
    },
  },
]);

const onGenerateReport = async () => {
  eventOptions.value = [];
  open({
    title: '生成报告',
    request: async (params: any) => {
      params.projectId = projectId.value;
      await getGenerateReport(params);
      tableRef.value.refresh();
    },
    defaultValue: {
      reportType: '1',
    },
  });
};

// 预览PDF
const loading = ref(true);
const visible = ref(false);
const pdfUrl = ref('');
const onPreview = (record: any) => {
  loading.value = false;
  getEarthquakeReport(
    {
      docType: 'pdf',
      reportId: record.reportId,
    },
    true,
  ).then((res: any) => {
    pdfUrl.value = window.URL.createObjectURL(
      new Blob([res.data], { type: 'application/pdf' }),
    );
    loading.value = true;
  });
  visible.value = true;
};

const onDownload = async (record: any) => {
  await getEarthquakeReport(
    {
      docType: 'docx',
      reportId: record.reportId,
    },
    false,
  );
  message.success('下载成功');
};
</script>

<style lang="scss" scoped></style>
